import button as button
import pygame,time
from random import *


#设置x和y
class Position(object):
    def __init__(self,x,y):
        self.x=x
        self.y=y

#随机生成食物
def new_food(head):
    while True:
        new_food=Position(randint(1,48)*20,randint(1,28)*20)#指定范围内的整数
        if new_food.x!=head.x and new_food.y!=head.y:#食物坐标和蛇头坐标不重合
            break
        else:
            continue
    return new_food

#绘制贪吃蛇和食物
def rect(color,position):
    pygame.draw.circle(window,color,(position.x,position.y),10)#画圆 直径

#退出游戏
def exit_end():
    pygame.quit()
    quit()

#显示得分
def show_end():
    #窗口大小
    small_window=pygame.display.set_mode((960,600))
    init_background=pygame.image.load("init_bgimg.jpg")
    small_window.blit(init_background,(0,0))
    #标题
    pygame.display.set_caption("贪吃蛇大冒险")
    #背景图片
    font = pygame.font.SysFont("simHei", 40)
    font1 = font.render('游戏结束! 你的得分为: %s' % score, False, black)
    small_window.blit(font1,(250,200))
    pygame.display.update()
    time.sleep(2)
    #pygame.quit()
    #sys.exit()
    into_game()
#死亡
def die_snake(head,snake_body):
    die_flag=False
    #遍历蛇身列表
    for body in snake_body[1:]:
        # 如果蛇头的xy和蛇身xy相等，则判定相撞，设置flag为ture
        if head.x == body.x and head.y == body.y:
            die_flag = True

    # 若蛇头的xy在显示窗体外，或flag为true，则显示结束界面，并退出游戏
    if head.x < 0 or head.x > 960 or head.y < 0 or head.y > 600 or die_flag:
        show_end()

#游戏模式
def start_game():
    global score#存分数
    global color
    color = (randint(10, 255), randint(10, 255), randint(10, 255))
    #贪吃蛇初始方向
    run_direction="right"
    run=run_direction
    #实例化贪吃蛇和食物
    head=Position(160,160)
    #初始化蛇身长度 3
    snake_body=[Position(head.x,head.y+20),Position(head.x, head.y + 40), Position(head.x, head.y + 60)]
    #初始化食物位置
    food=Position(300,300)

    while True:
        window.blit(game_background,(0,0))
        #监听玩家按键
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                show_end()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_UP:
                    run_direction = "up"
                elif event.key == pygame.K_RIGHT:
                    run_direction = "right"
                elif event.key == pygame.K_LEFT:
                    run_direction = "left"
                elif event.key == pygame.K_DOWN:
                    run_direction = "down"

        rect(color,food)#食物
        rect(black,head)#蛇头
        for pos in snake_body:
            rect(white,pos)#蛇身

        #判断贪吃蛇运动方向和玩家按键是否一样
        if run == "up" and not run_direction == "down":
            run = run_direction
        elif run == "down" and not run_direction == "up":
            run = run_direction
        elif run == "left" and not run_direction == "right":
            run = run_direction
        elif run == "right" and not run_direction == "left":
            run = run_direction

        #蛇头插入蛇身列表
        snake_body.insert(0,Position(head.x,head.y))
        #根据玩家按键进行蛇头位置的更新
        if run == "up":
            head.y -= 20
        elif run =="down":
            head.y +=20
        elif run =="left":
            head.x -=20
        elif run =="right":
            head.x +=20
        #判断是否死亡
        die_snake(head,snake_body)
        #判断蛇头坐标是否和食物坐标一致  若一致 加分
        if head.x == food.x and head.y == food.y:
            score += 1
            food = new_food(head)
            color = (randint(10, 255), randint(10, 255), randint(10, 255))
        else:
            snake_body.pop()#移除列表最后一个元素 并 返回值

        font = pygame.font.SysFont("simHei", 25)
        mode_title = font.render('游戏进行中', False, grey)
        socre_title = font.render('得分: %s' % score, False, grey)
        window.blit(mode_title, (50, 30))
        window.blit(socre_title, (50, 65))
        pygame.display.update()
        # 通过帧率设置贪吃蛇速度
        clock.tick(8)

#监听键盘输入
""" msg: 按钮信息，x: 按钮的x轴，y: 按钮的y轴，w: 按钮的宽，h: 按钮的高
ic: 按钮初始颜色，ac: 按钮按下颜色，action: 按钮按下的动作"""
def button (msg, x, y, w, h, ic, ac, action=None):
    mouse = pygame.mouse.get_pos()#获取鼠标光标位置
    click = pygame.mouse.get_pressed()#获取键盘按键情况
    if x + w > mouse[0] > x and y + h > mouse[1] > y:
        pygame.draw.rect(window, ac, (x, y, w, h))
        if click[0] == 1 and action != None:
            action()
    else:
        pygame.draw.rect(window, ic, (x, y, w, h))

    #设置按钮样式
    font = pygame.font.SysFont('simHei', 20)
    font1 = font.render(msg, True, white)
    font2 = font1.get_rect()
    font2.center=((x+(w/2)),(y+(h/2)))
    window.blit(font1,font2)

#游戏初始界面
def into_game():
    global score
    score=0
    into=True
    while into:
        window.blit(init_background,(0,0))#背景坐标
        for event in pygame.event.get(): # 从队列中获取事件
            if event.type == pygame.QUIT:
                exit_end()#退出

        font=pygame.font.SysFont("simHei",50)#设置字体与大小
        #初始化界面文字
        font1=font.render('欢迎来到贪吃蛇大冒险!',True,black)
        font2=font1.get_rect()#获取属性
        font2.center=((width/2),200)#对齐
        window.blit(font1,font2)
        button("开始游戏",370,370,200,60,blue,red,start_game) # x y w h
        button("退出",370,450,200,60,violte,red,exit_end)
        pygame.display.update()
        clock.tick(15)#最大帧率

if __name__=="__main__":
    # 定义游戏颜色
    white = (255, 255, 255)  # 蛇身
    red = (200, 0, 0)  # 点击后
    green = (0, 128, 0)  # 食物
    blue = (0, 202, 254)  # 开始
    violte = (194, 8, 234)  # 退出
    black = (0, 0, 0)  # 字体 and 蛇头
    grey = (129, 131, 129)  # 字体2
    score=0
    # 设计初始化窗口
    width = 960
    height = 600
    window = pygame.display.set_mode((width, height))
    # 定义游戏名字
    pygame.display.set_caption("贪吃蛇大冒险")
    # 背景图片 进入界面和游戏界面
    init_background = pygame.image.load("init_bgimg.jpg")
    game_background = pygame.image.load("bgimg.jpg")
    # 创建一个时钟
    clock = pygame.time.Clock()
    # 初始化
    pygame.init()
    # 初始界面
    into_game()




